﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LBKDHelper.Models;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin.BillPlugins
{
    /// <summary>
    /// 鹿奔
    /// </summary>
    [HotUpdate, Description("物料清单表单插件")]
    public class BOMBillPlugin : AbstractBillPlugIn
    {
        /// <summary>
        /// 单据头-标准BOM
        /// </summary>
        private readonly ElementKeySchema F_dev_normal = new ElementKeySchema
        {
            DbKey = "F_DEV_NORMAL",
            FormKey = "F_dev_normal",
            OrmKey = "F_dev_normal"
        };

        private readonly ElementKeySchema FMATERIALID = new ElementKeySchema
        {
            DbKey = "FMATERIALID",
            FormKey = "FMATERIALID",
            OrmKey = "MATERIALID"
        };

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            var id = View.Model.GetPKValue()?.ToString() ?? "0";
            var material = View.Model.DataObject[FMATERIALID.OrmKey] as DynamicObject;
            var materialId = material?["Id"]?.ToString() ?? "0";
            var existed = DBUtils.ExecuteScalar(Context, $@"select 1
                from T_ENG_BOM
                where FID != '{id}'
                and FMATERIALID = '{materialId}'
                and F_DEV_NORMAL = '1';", 0);
            if (existed == 0)
            {
                // 如果没有其它标准BOM，则设置当前BOM为标准BOM
                View.Model.SetValue(F_dev_normal.FormKey, true);
                View.UpdateView(F_dev_normal.FormKey);
            }

            var setted = View.Model.GetValue(F_dev_normal.FormKey) as bool? ?? false;
            if (setted)
            {
                // 如果当前BOM为标准BOM，则去掉其它标准BOM
                DBUtils.Execute(Context, $@"update T_ENG_BOM
                    set F_DEV_NORMAL = '0'
                    where FID != '{id}'
                    and FMATERIALID = '{materialId}';");
            }
            //View.ShowMessage("ID是：" + materialId);
        }
    }
}
